package com.olocat.cjx.nsims.controller

import com.alibaba.fastjson.JSON
import com.olocat.cjx.nsims.dao.DoctorRepository
import com.olocat.cjx.nsims.dao.UserRepository
import com.olocat.cjx.nsims.pojo.entry.EntryDoctor
import com.olocat.cjx.nsims.pojo.personnel.Doctor
import com.olocat.cjx.nsims.pojo.personnel.User
import com.olocat.cjx.nsims.service.DoctorService
import com.olocat.cjx.nsims.service.UserService
import com.olocat.cjx.nsims.util.Response
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.*
import javax.annotation.Resource

@RestController
class DoctorController {

    @Resource
    lateinit var doctorService: DoctorService
    @Resource
    lateinit var doctorRepository: DoctorRepository
    @Resource
    lateinit var userService:UserService
    var log = LoggerFactory.getLogger("DoctorController")!!

    @GetMapping("/api/doctor/get")
    fun get(id: String?, department:Int?): Response {
        return if (id == null) {
            if(department == null)
            Response.builder(doctorService.list())
            else
            Response.builder(doctorService.getDoctorByDepartment(department))
        } else {
            log.info("获取 id=$id 医生的信息")
            Response.builder(doctorService.getById(id))
        }
    }
    @GetMapping("/api/doctor/name")
    fun getDoctorByName(name: String):Response{
       return Response.builder(doctorService.getDoctorByName(name))
    }
    @PostMapping("/api/doctor/entry")
    fun add(@RequestBody json: String?): Response {
        log.info("添加医生信息 json: $json")
        val doctor = JSON.parseObject(json, Doctor::class.java)
//        nurseService.save(nurse)
        doctorRepository.save(doctor)
        val user = User()
        user.telephone = doctor.phone
        user.name = doctor.name
        userService.saveDoctorUser(user)
        return Response.builder()
    }
    @PostMapping("/api/doctor/save")
    fun save(@RequestBody json: String): Response {
        val doctor = JSON.parseObject(json, Doctor::class.java)
        doctorService.updateById(doctor)
        return Response.builder()
    }

    @DeleteMapping("/api/doctor/del")
    fun del(id: String): Response {
        log.info("delete doctor id: $id")
        doctorService.removeById(id)
        return Response.builder()
    }

    @GetMapping("/api/doctor/query")
    fun getByName(name: String?): Response {
        return if (name == null) {
            log.info("查询字段为空")
            Response.builder()
        } else {
            log.info("根据姓名查询医生 $name")
            Response.builder(doctorService.getByName(name))
        }
    }
    @GetMapping("/api/doctor/department")
    fun getDoctorByDepartment(department: Int):Response{
        val doctor = doctorService.getDoctorByDepartment(department)
        println("根据部门查的医生" + doctor)
        return Response.builder(doctor)
    }
}